package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

	@Autowired
	private UserAccountMapper userAccountMapper;
	@Autowired
	private OrderInfoFeignClient orderInfoFeignClient;

	@Autowired
	private UserAccountDetailMapper userAccountDetailMapper;

	@Override
	public BigDecimal getAvailableAmount(Long userId) {
		LambdaQueryWrapper<UserAccount> lambdaQueryWrapper = new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, userId).select(UserAccount::getAvailableAmount);
		return this.getOne(lambdaQueryWrapper).getAvailableAmount();
	}

	@Override
	public Boolean checkAndDeduct(AccountDeductVo accountDeductVo) {
		try {
//		先检查库存并扣款
			int row = userAccountMapper.checkAndDeduct(accountDeductVo.getUserId(), accountDeductVo.getAmount());
			if (row == 0){
	//			如果影响的行数大于0，就表示扣款失败
				log.error("用户{}扣款失败，余额不足", accountDeductVo.getUserId());
				throw new GuiguException(ResultCodeEnum.ACCOUNT_LESS);
			}
//		保存订单详细信息
//		生成一个用户账户详情对象
			UserAccountDetail userAccountDetail = new UserAccountDetail();
//		为属性赋值
			userAccountDetail.setUserId(accountDeductVo.getUserId());
			userAccountDetail.setAmount(accountDeductVo.getAmount());
			userAccountDetail.setOrderNo(accountDeductVo.getOrderNo());
			userAccountDetail.setTitle(accountDeductVo.getContent());
			userAccountDetail.setTradeType(SystemConstant.ACCOUNT_TRADE_TYPE_MINUS);
//		往数据库添加数据
			userAccountDetailMapper.insert(userAccountDetail);
//			执行完成后，返回true
			return true;
		} catch (Exception e) {
			e.getMessage();
		}
		return false;
	}
}
